package gac.helloworld;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AlarmListActivity extends ListActivity {
	private static final int ACTIVITY_CREATE = 0;
	private static final int ACTIVITY_EDIT = 1;
	private AlarmDbAdapter mDbHelper;
	private ArrayList<AlarmData> mAlarmData = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);

		// get stored alarm data
		mDbHelper = new AlarmDbAdapter(this);
		mDbHelper.open();
		fillAlarmData();

		ListView lv = getListView();
		lv.setItemsCanFocus(true); // necessary for item selection to work

		// add the "create alarm" button
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup alarm_bar = (ViewGroup) inflater.inflate(R.layout.alarm_bar, lv, false);

		lv.addFooterView(alarm_bar, null, false);

		AlarmAdapter mAdapter = new AlarmAdapter(this, R.layout.alarm_row, mAlarmData);
		setListAdapter(mAdapter);
	}

	private class AlarmAdapter extends ArrayAdapter<AlarmData> {

		private ArrayList<AlarmData> items;

		public AlarmAdapter(Context context, int textViewResourceId, ArrayList<AlarmData> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int position_final = position;
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.alarm_row, null);
			}
			final AlarmData o = items.get(position);
			if (o != null) {
				TextView destTV = (TextView) v.findViewById(R.id.destination_text);
				TextView arrivalTimeTV = (TextView) v.findViewById(R.id.arrival_time_text);
				TextView estimatedTimeTV = (TextView) v.findViewById(R.id.estimated_leave_text);
				Button navigationButton = (Button) v.findViewById(R.id.start_nav);

				if (destTV != null) {
					destTV.setText(getString(R.string.destination) + ":\t" + o.getDestination());
				}
				if (arrivalTimeTV != null) {
					arrivalTimeTV.setText(getString(R.string.arrival_time) + ":\t" + o.getAlarmDateString() + ", " + o.getArrivalTimeString());
				}

				if(estimatedTimeTV != null){
					estimatedTimeTV.setText(getString(R.string.estimated_time) + ":\t"); //change to actual text
				}

				if (navigationButton != null) {
					navigationButton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + o.getDestination()));
							startActivity(i);
						}
					});
				}
			}

			v.setClickable(true);
			v.setFocusable(true);
			v.setLongClickable(true);
			v.setBackgroundResource(android.R.drawable.menuitem_background);
			v.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					editAlarm(o.getId());
				}

			});

			v.setOnLongClickListener(new View.OnLongClickListener() {
				public boolean onLongClick(View v) {
					final CharSequence[] options = { "Turn Alarm Off", "Edit Alarm", "Delete Alarm" };
					if (!o.isOn()) {
						options[0] = "Turn Alarm On";
					}
					AlertDialog.Builder builder = new AlertDialog.Builder(AlarmListActivity.this);
					builder.setTitle("Alarm to " + o.getDestination());
					builder.setItems(options,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int item) {
									if (item == 0) // toggle alarm on/off
									{
										Cursor cursor = mDbHelper.fetchAlarm(o
												.getId());
										startManagingCursor(cursor);
										if (o.isOn()) {
											mDbHelper.updateAlarm(
													o.getId(), cursor.getString(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DESTINATION)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_HOUR)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MINUTE)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_WARNTIME)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MONTH)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DAY)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_YEAR)),
													0);
										} else {
											mDbHelper.updateAlarm(
													o.getId(),
													cursor.getString(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DESTINATION)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_HOUR)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MINUTE)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_WARNTIME)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MONTH)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DAY)),
													cursor.getInt(cursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_YEAR)),
													1);
										}
										stopManagingCursor(cursor);
									} else if (item == 1) // edit alarm
									{
										editAlarm(o.getId());
									} else if (item == 2) // delete alarm
									{
										AlertDialog.Builder alert = new AlertDialog.Builder(AlarmListActivity.this);
										alert.setTitle("Delete Alarm");
										alert.setMessage("Are you sure you want to delete this alarm?");
										alert.setPositiveButton(
												"OK", new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int whichButton) {
														mDbHelper.deleteAlarm(o.getId());
														fillAlarmData();
													}
												});

										alert.setNegativeButton(
												"Cancel",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int whichButton) {
														// Canceled.
													}
												});

										alert.show();
									}
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
					return true;
				}

			});

			return v;
		}
	}

	// make a database call to populate mAlarmData
	private void fillAlarmData() {
		mAlarmData = new ArrayList<AlarmData>();
		Cursor cur = mDbHelper.fetchAllAlarms();
		startManagingCursor(cur);

		// read data out of the database
		if (cur.moveToFirst()) {
			do {
				// Get the field values
				long id = cur.getLong(cur.getColumnIndex(AlarmDbAdapter.KEY_ROWID));
				String dest = cur.getString(cur.getColumnIndex(AlarmDbAdapter.KEY_DESTINATION));
				int hour = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_HOUR));
				int minute = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_MINUTE));
				int warntime = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_WARNTIME));
				int month = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_MONTH));
				int day = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_DAY));
				int year = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_YEAR));
				int isOn = cur.getInt(cur.getColumnIndex(AlarmDbAdapter.KEY_ISON));

				mAlarmData.add(new AlarmData(id, dest, hour, minute, warntime, month, day, year, isOn));
			} while (cur.moveToNext());
		}

		// create an adapter and set it to display
		AlarmAdapter mAdapter = new AlarmAdapter(this, R.layout.alarm_row, mAlarmData);
		setListAdapter(mAdapter);

	}

	// create an alarm in response to a "create alarm" click
	public void editAlarm(Long id) {
		Intent i = new Intent(getApplicationContext(), EditAlarmActivity.class);
		i.putExtra(AlarmDbAdapter.KEY_ROWID, id);
		startActivityForResult(i, ACTIVITY_EDIT);
	}

	public void createAlarm(View v) {
		Intent i = new Intent(getApplicationContext(), EditAlarmActivity.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}
	
	public void testLoc(View v) {
		MapHandler map = new MapHandler(this, "New York, NY", 3, 30, 9, 10, 2011, 0);
		//(Activity a, String destination, int hour, int minute, int month, int day, int year, int buffer)
		int time = map.calculateTime();
		boolean leave = map.isTimeToLeave();
		Toast.makeText(this, "IS TIME TO LEAVE = ", Toast.LENGTH_LONG).show();
		Log.v("",""+time);
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillAlarmData();
	}
}